package start.demo01.datatype.json.interfaces;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public abstract class JSONBuilder implements Builder<JSONObject> {

    protected JSONObject jsonObject;
    protected String cmd;

    public JSONBuilder(String cmd) {
        this.cmd = cmd;
    }

    public void create(String cmd) {
        int i = cmd.indexOf('[');
        int e = cmd.indexOf(']');
        String key = cmd.substring(i + 1, e);
        String var = cmd.substring(e + 1);
        if ("jsonObject".equals(key)) {
            jsonObject=new JSONObject();
        }
    }

    @Override
    public JSONObject get() {
        return jsonObject;
    }

    //builde{val.k}
    public static JSONObject builde(JSONObject origin, String cmd) {
        Object object = origin;
        int i = cmd.indexOf('{');
        int e = cmd.indexOf('}');
        String key = cmd.substring(i + 1, e);
        String[] split = key.split("\\.");
        for (String s : split) {
            if (s.matches("\\w+")) {
                JSONObject jsonObject;
                if (object instanceof JSONArray) {
                     jsonObject= new JSONObject();
                    ((JSONArray) object).add(jsonObject);
                } else {
                    if(((JSONObject) object).containsKey(s))
                        continue;
                    jsonObject = new JSONObject();
                    ((JSONObject) object).put(s, jsonObject);
                }
                object = jsonObject;
            } else if (s.matches("\\[\\]")) {
                JSONArray array = new JSONArray();
                ((JSONArray) object).add(array);
                object = array;
            } else if (s.matches("\\[.+\\]")) {
                JSONArray array = new JSONArray();
                ((JSONObject) object).put(s.substring(1, s.length() - 1), array);
                object = array;
            }
        }
        return null;
    }

    public String getCmd() {
        return cmd;
    }

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        builde(jsonObject, "builde{val.k}");
        System.out.println("ss");
    }
}
